<template>
  <ga-modal
    v-model:visible="visible"
    title-align="start"
    :width="600"
    @close="handleCancel(formRef)"
  >
    <template #title>{{ curId ? "编辑子网" : "创建子网" }}</template>
    <ga-spin style="width: 100%" :loading="loading">
      <ga-form ref="formRef" :model="formData">
        <ga-form-item
          field="name"
          label="子网名称"
          label-col-flex="70px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-input v-model="formData.name" placeholder="请输入子网名称" />
        </ga-form-item>
        <ga-form-item
          label-col-flex="70px"
          style="margin-bottom: 0"
          label="CIDR"
          :rules="[RULE.NOT_NULL]"
        >
          <ga-form-item
            field="ip"
            label="ip"
            hide-label
            :rules="[
              { required: true, message: '必填项不能为空' },
              { validator: validator.ip, trigger: ['change', 'input'] },
            ]"
            style="width: 200px"
          >
            <ga-input v-model="formData.ip" placeholder="请输入地址" />
          </ga-form-item>
          <p style="margin: 0 7px 16px">/</p>
          <ga-form-item
            hide-label
            field="cidrPart"
            label="cidrPart"
            label-col-flex="70px"
            style="width: 200px"
            :rules="[RULE.NOT_NULL]"
            :validate-trigger="['change']"
          >
            <ga-input-number
              :max="32"
              v-model="formData.cidrPart"
              placeholder="请输入掩码位"
            />
          </ga-form-item>
        </ga-form-item>
        <ga-form-item
          label-col-flex="70px"
          label="地址池"
          field="ipPools"
          :rules="[RULE.NOT_NULL]"
          :content-flex="false"
          style="margin: 0"
        >
          <ga-form-item v-for="(item, index) in formData.ipPools" :key="index" hide-label>
            <ga-input
              v-model="item.start"
              placeholder="输入satrt地址"
              style="width: 200px"
            />
            <p style="margin: 0 7px">-</p>
            <ga-input
              v-model="item.end"
              allow-clear
              style="width: 200px; margin-right: 8px"
              placeholder="请输入end地址"
            />
            <ga-link @click="formData.ipPools.push({})" v-if="index === 0">添加</ga-link>
            <ga-link status="danger" v-else @click="formData.ipPools.splice(index, 1)"
              >删除</ga-link
            >
          </ga-form-item>
        </ga-form-item>
        <ga-form-item
          field="gatewayAdd"
          label="网关"
          label-col-flex="70px"
          :rules="[
            { required: true, message: '必填项不能为空' },
            { validator: validator.ip, trigger: ['change', 'input'] },
          ]"
        >
          <ga-input v-model="formData.gatewayAdd" placeholder="请输入名称" />
        </ga-form-item>
        <ga-form-item field="isSame" label="时钟源地址" label-col-flex="70px">
          <ga-checkbox v-model="formData.isSame" :value="true" @change="handleChange">
            与网关一致
          </ga-checkbox>
        </ga-form-item>
        <ga-form-item
          field="dateHost"
          v-if="!formData.isSame"
          label-col-flex="70px"
          :rules="[{ validator: validator.ip, trigger: ['change', 'input'] }]"
        >
          <ga-input v-model="formData.dateHost" placeholder="请输入时钟源地址" />
        </ga-form-item>
        <ga-form-item field="bkCloud" label="蓝鲸云区域" label-col-flex="70px">
          <ga-select
            size="small"
            v-model="formData.bkCloud"
            placeholder="请选择蓝鲸云区域"
          >
            <ga-option
              v-for="item in bkCloudList"
              :key="item.bkCloudId"
              :value="item.bkCloudId"
            >
              {{ item.bkCloudName }}
            </ga-option>
          </ga-select>
        </ga-form-item>
        <ga-form-item field="dnsAdd1" label="DNS1" label-col-flex="70px">
          <ga-input v-model="formData.dnsAdd1" placeholder="请输入DNS1" />
        </ga-form-item>
        <ga-form-item field="dnsAdd2" label="DNS2" label-col-flex="70px">
          <ga-input v-model="formData.dnsAdd2" placeholder="请输入DNS2" />
        </ga-form-item>
        <ga-form-item field="description" label="备注" label-col-flex="70px">
          <ga-textarea v-model="formData.description" placeholder="请输入内容" />
        </ga-form-item>
      </ga-form>
    </ga-spin>
    <template #footer>
      <ga-button @click="visible = false">取消</ga-button>
      <ga-button type="primary" @click="handleOk">确定</ga-button>
    </template>
  </ga-modal>
</template>

<script setup>
import { ref, defineEmits, reactive } from "vue";
import { editLayer2Subnet, createLayer2Subnet } from "@/api/layer2subnet";
import { getBkCloudList } from "@/api/pluginMgmt";
import { Message } from "@garco-design/web-vue";
import { RULE, validator } from "@/constant/validators";
import useLoading from "@/hooks/loading";
import { calNBFL } from "@/utils/index";

const { loading, setLoading } = useLoading(false);
const formRef = ref(null);
const bkCloudList = ref([]);
const formData = reactive({
  name: "",
  cidr: "",
  ip: "",
  enabled: 0,
  maskAdd: "",
  cidrPart: "",
  dnsAdd1: "",
  dnsAdd2: "",
  isSame: true,
  ipPools: [{}],
  dateHost: "",
  bkCloud: "",
  gatewayAdd: "",
  description: "",
});

const visible = ref(false);
const curId = ref("");

const handleCidr = (value) => {
  if (!value) return ["", ""];
  const parts = value.split("/");
  return [parts[0], parts[1]];
};
// 获取蓝鲸云区域列表
const fetchBkCloudData = async () => {
  try {
    const { data } = await getBkCloudList({ limit: -1 });
    bkCloudList.value = data || [];
  } catch (err) {
    console.log(err);
  }
};
const open = async (record) => {
  visible.value = true;
  fetchBkCloudData();
  if (record && record?.id) {
    setLoading(true);
    curId.value = record.id;
    Object.keys(formData).forEach((item) => {
      if (item === "ip" || item === "cidrPart") {
        const [ipPart, portPart] = handleCidr(record.cidr);
        formData.ip = ipPart || "";
        formData.cidrPart = Number(portPart) ? Number(portPart) : 0;
      } else if (item === "ipPools") {
        formData[item] = JSON.parse(record[item]) || [];
      } else {
        formData[item] = record[item];
        formData.isSame = formData.gatewayAdd === formData.dateHost;
      }
    });
    setLoading(false);
  }
};
// 处理方法
const handleChange = (val) => {
  formData.dateHost = val ? formData.gatewayAdd : "";
};
// 保存
const emits = defineEmits(["fetchData"]);
const handleOk = async () => {
  const res = await formRef.value?.validate();
  if (!res) {
    try {
      const netInfo = buildNetInfo(formData);
      const { code } = !curId.value
        ? await createLayer2Subnet(netInfo)
        : await editLayer2Subnet(curId.value, netInfo);
      if (code === 20000) Message.success("操作成功");
      emits("fetchData");
    } finally {
      visible.value = false;
    }
  }
};
// 处理buildNetInfo方法
const buildNetInfo = (formData) => {
  const ipPools = Array.isArray(formData.ipPools)
    ? JSON.stringify(formData.ipPools)
    : "[]";
  formData.cidr = `${formData.ip}/${formData.cidrPart}`;
  const maskAdd = formData.cidr ? calNBFL(formData.cidr)?.mask : "";
  formData.dateHost = formData.isSame ? formData.gatewayAdd : formData.dateHost;
  const {
    name,
    cidr,
    dnsAdd1,
    dnsAdd2,
    dateHost,
    enabled,
    gatewayAdd,
    description,
    bkCloud,
  } = formData;
  return {
    name,
    cidr,
    enabled,
    maskAdd,
    dnsAdd1,
    dnsAdd2,
    ipPools,
    dateHost,
    gatewayAdd,
    description,
    bkCloud,
  };
};
const handleCancel = (formEl) => {
  curId.value = "";
  formEl.resetFields();
};
defineExpose({ open });
</script>

<style lang="scss" scoped></style>
